package dao;

import ucm.User;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;

/**
 *
 * @author Adam Scarr
 * @since r1
 */
public class LDAPAuthenticator extends Authenticator {
    protected LDAPAuthenticator() {

    }

    public static void init() {
        setInstance(new LDAPAuthenticator());
    }

    public User authenticateUser(String username, String password) {
        if(username.length() == 0 || password.length() == 0) {
            return null;
        }

		Hashtable<String, String> env = new Hashtable<String, String>();

		env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL,"ldap://ldap.jcu.edu.au:389/dc=jcu,dc=edu,dc=au");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, "uid=" + username + ",ou=Users,dc=jcu,dc=edu,dc=au");
		env.put(Context.SECURITY_CREDENTIALS, password);

		try {
			DirContext ctx;

			ctx = new InitialDirContext(env);
			System.out.println("Logged in!");

			Attributes attrs = ctx.getAttributes("uid=" + username + ",ou=Users");
			System.out.println("cn: " + attrs.get("cn").get());

		} catch(javax.naming.AuthenticationException e) {
			System.out.println("Authentication Exception: " + e);
			System.exit(1);
		} catch(javax.naming.NamingException e) {
			System.out.println("Naming Exception error: " + e);
			System.exit(1);
		}

        try {
            user = MyDAO.getInstance().getUser(username, password);
        } catch (MyDAOException e) {
            e.printStackTrace();
        }

        return user;
    }
}
